package yongxin.controller.processreport;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.core.util.ResourceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import yongxin.entity.annealer.AnnealerEntity;
import yongxin.entity.matchinegroup.MatchinegroupEntity;
import yongxin.entity.notice.NoticeEntity;
import yongxin.entity.process.ProcessEntity;
import yongxin.entity.processreport.ProcessReportEntity;
import yongxin.entity.temp_record.TempRecordEntity;
import yongxin.entity.workshop.WorkshopEntity;
import yongxin.service.annealer.AnnealerServiceI;
import yongxin.service.process.ProcessServiceI;
import yongxin.service.processreport.ProcessReportServiceI;
import yongxin.service.tasks.TasksServiceI;
import yongxin.service.workshop.WorkshopServiceI;

/**   
 * @Title: Controller
 * @Description: 工序汇报
 * @author zhangdaihao
 * @date 2015-02-05 14:03:13
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/annealerReport004Controller")
public class AnnealerReport004Controller extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(AnnealerReport004Controller.class);

	@Autowired
	private AnnealerServiceI annealerService;
	@Autowired
	private ProcessReportServiceI processReportService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ProcessServiceI processService;
	@Autowired
	private TasksServiceI tasksService;
	@Autowired
	private WorkshopServiceI workshopService;
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 工序汇报列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "processReport")
	public ModelAndView processReport(HttpServletRequest request) {
		String process=request.getParameter("process");

		request.setAttribute("process", process);
		return new ModelAndView("yongxin/process/annealerReportList_p4");
		
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(AnnealerEntity annealer,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		
		
		CriteriaQuery cq = new CriteriaQuery(AnnealerEntity.class, dataGrid);
		//查询条件组装器
	
		if( StringUtil.isEmpty(annealer.getFstate())){
		cq.eq("fstate", "1");
		}
		TSUser user = ResourceUtil.getSessionUser();//(TSUser) request.getSession().getAttribute("loginUser");
	/*	if (user.getUserName().contains("bxg"))
		{
			cq.like("fbcph", "S%");
			
		} else if (user.getUserName().contains("tg"))
		{
			cq.like("fbcph", "Y%");
		}*/
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, annealer, request.getParameterMap());
		this.systemService.getDataGridReturn(cq, true);
	
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除工序汇报
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(ProcessReportEntity processReport, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		processReport = systemService.getEntity(ProcessReportEntity.class, processReport.getId());
		message = "工序汇报删除成功";
		processReportService.delete(processReport);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加工序汇报
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(ProcessReportEntity processReport, AnnealerEntity annealer,HttpServletRequest request) {
		
		
		AjaxJson j = new AjaxJson();
		
		String fstate = request.getParameter("fstate");
		String note = request.getParameter("fnote");
		note = (note==null)? "":note;
		String[] fbcphs = request.getParameterValues("fbcph");
		String[] fwlnames = request.getParameterValues("fwlname");
		
		String[] fnprocess = request.getParameterValues("nprocess");
		String[] pids = request.getParameterValues("pid");
		String[] ftrkds = request.getParameterValues("ftrkd");
		String[] ftrhds = request.getParameterValues("ftrhd");
		String[] ftrzls = request.getParameterValues("ftrzl");
		
		TSUser user = ResourceUtil.getSessionUser();//(TSUser) request.getSession().getAttribute("loginUser");
		
		if (StringUtil.isNotEmpty(annealer.getId()))
		{
			message = "更新成功";
			try
			{

				// MyBeanUtils.copyBeanNotNull2Bean(annealer, a);
				// AnnealerEntity a = annealerService.get(AnnealerEntity.class,
				// annealer.getId());
				if (StringUtil.isNotEmpty(annealer.getFsdwd()))
				{
					annealer.setFoperator1(user.getUserName());
				}
				if (annealer.getFswsj() != null)
				{
					annealer.setFoperator2(user.getUserName());
				}
				if (annealer.getFbwsj() != null)
				{
					annealer.setFoperator3(user.getUserName());
				}
				if (annealer.getFdzsj() != null)
				{
					annealer.setFoperator4(user.getUserName());
				}
				if (StringUtil.isNotEmpty(annealer.getFdzwd()))
				{
					annealer.setFoperator5(user.getUserName());
				}
				if (annealer.getFslsj() != null)
				{
					annealer.setFoperator6(user.getUserName());
				}
				if (StringUtil.isNotEmpty(annealer.getFslwd()))
				{
					annealer.setFoperator7(user.getUserName());
				}
				annealer.setFnote(note);
				annealerService.saveOrUpdate(annealer);
				systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
				
			} catch (Exception e)
			{
				e.printStackTrace();
				message = "更新失败";
			}

			// 退火炉汇报
			if (fstate.equals("2"))
			{
				for (int i = 0; i < fbcphs.length; i++)
				{

					if (!fnprocess.equals("over"))
					{
						ProcessReportEntity nprocessReport = new ProcessReportEntity();
						nprocessReport.setFwlname(fwlnames[i]);
						nprocessReport.setCprocess(fnprocess[i]);
						nprocessReport.setFbcph(fbcphs[i]);
						nprocessReport.setFtrhd(ftrhds[i]);
						nprocessReport.setFtrkd(ftrkds[i]);
						nprocessReport.setFtrzl(ftrzls[i]);
						nprocessReport.setFstate("0");
						processReportService.save(nprocessReport);

						ProcessEntity entity = new ProcessEntity();
						entity.setFreportid(nprocessReport.getId());
						entity.setFbcph(fbcphs[i]);
						entity.setFprocess(fnprocess[i]);
						processService.save(entity);

						ProcessReportEntity p = processReportService.get(ProcessReportEntity.class, pids[i]);
						p.setNprocess(fnprocess[i]);
						p.setFstate("2");
						p.setFcchd(p.getFtrhd());
						p.setFcckd(p.getFtrkd());
						p.setFcczl(p.getFtrzl());
						p.setFbfzl("0");
						p.setFrate("100%");
						p.setfNextReportId(nprocessReport.getId());
						processReportService.saveOrUpdate(p);

					} else
					{

						ProcessEntity entity = new ProcessEntity();
						entity.setFbcph(fbcphs[i]);
						entity.setFprocess(fnprocess[i]);
						processService.save(entity);

					}
				}
			}else if(fstate.equals("1")){   // 保存
				
				for (int i = 0; i < fbcphs.length; i++)
				{
					ProcessReportEntity p = processReportService.get(ProcessReportEntity.class, pids[i]);
					p.setNprocess(fnprocess[i]);
					processReportService.saveOrUpdate(p);
				}
				
			}
		}

		j.setMsg(message);
		return j;
	}

	
	
	@RequestMapping(params = "returnReport4")
	@ResponseBody
	public AjaxJson returnReport4(AnnealerEntity annealer, HttpServletRequest request)
	{

		AjaxJson j = new AjaxJson();

		// 获取炉子id 、 炉内卷号id
		String id = request.getParameter("id");
		String fhbids = request.getParameter("fhbid");

		String[] fhbid = { fhbids };

		if (fhbids.contains(","))
		{
			fhbid = fhbids.split(",");
		}

		String sql4 = " select fstate from t_processreport where  id = ? ";

		// 反汇报之前判断炉内卷号在下道工序完工否
		for (int i = 0; i < fhbid.length; i++)
		{

			ProcessReportEntity p = processReportService.getEntity(ProcessReportEntity.class, fhbid[i]);
			
			if (StringUtil.isNotEmpty(p.getfNextReportId()))
			{   
				ProcessReportEntity p2 = processReportService.getEntity(ProcessReportEntity.class, p.getfNextReportId());

				if (p2.getFstate().equals("2") &&  p2.getNprocess().equals("over"))    // 卷号在下道工序即结束
				{
					message = "反汇报失败，炉内有卷号在下道工序已结束";
					j.setMsg(message);
					return j;

				} else
				{

					String value = String.valueOf(systemService.findOneForJdbc(sql4, p.getfNextReportId()).get("fstate"));

					if (value.equals("2"))
					{

						message = "反汇报失败，炉内有卷号在下道工序已汇报";
						j.setMsg(message);
						return j;

					} else if (value.equals("4"))
					{

						message = "反汇报失败，炉内有卷号在下道工序已装炉";
						j.setMsg(message);
						return j;
					} else if (value.equals("3"))
					{

						message = "反汇报失败，炉内有卷号在下道工序已分卷";
						j.setMsg(message);
						return j;
					}

				}
			} else
			{

				message = "反汇报失败";
				j.setMsg(message);
				return j;
			}
		}

		String sql = " delete from t_process where freportid = ? ";
		String sql2 = " delete from t_processreport where id = ? ";
		String sql3 = " update t_processreport set fstate = '4',FNextReportid = '' where id = ? ";

		String sql5 = " delete from t_process where fbcph = ?  and fprocess = 'over' ";
		String sql6 = " update t_tasks set fstate = '2',frate = NULL where fbcph = ? ";

		// 反汇报
		for (int i = 0; i < fhbid.length; i++)
		{

			ProcessReportEntity p = processReportService.getEntity(ProcessReportEntity.class, fhbid[i]);
			ProcessReportEntity p2 = processReportService.getEntity(ProcessReportEntity.class, p.getfNextReportId());
			
			String fbcph2 = p.getFbcph();
			if (p.getFbcph().contains("-")) // 卷号分卷了 得到母卷号
			{

				List<String> list = StringUtil.parseString2ListByCustomerPattern("-", p.getFbcph());
				fbcph2 = list.get(0);
			}
			if (p.getNprocess().equals("over")) // 本道工序即结束
			{
				systemService.executeSql(sql5, p.getFbcph());
				systemService.executeSql(sql6, fbcph2);
				systemService.executeSql(sql3, p.getId());
			} else
			{
				
				if (StringUtil.isNotEmpty(p2.getNprocess()) && p2.getFstate().equals("1"))   //  如果下一工序是纵剪或镀铬 则对应的t_cut t_chromate表记录
				{   
					
					if (p2.getNprocess().equals("p10"))  
					{
						String sql7 = " delete from t_cut where fbcph =  " ;
						systemService.executeSql(sql7, p2.getFbcph());
						
					} else if (p2.getNprocess().equals("p11"))
					{
						String sql8 = " delete from t_chromate where fbcph =  ? " ;
						systemService.executeSql(sql8, p2.getFbcph());
					}

				}
				
				
				systemService.executeSql(sql, p.getfNextReportId()); // 删工序
				systemService.executeSql(sql2, p.getfNextReportId()); // 删工序汇报记录
				systemService.executeSql(sql3, p.getId()); // 更改炉内卷号状态
			}

		}

		AnnealerEntity a = annealerService.getEntity(AnnealerEntity.class, id);
		a.setFstate("1");
		annealerService.saveOrUpdate(a);
		message = "反汇报成功";

		j.setMsg(message);
		return j;
	}

	/**
	 * 工序汇报列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(AnnealerEntity annealer, HttpServletRequest req) {
		
		List<ProcessReportEntity> list=new ArrayList<ProcessReportEntity>();
		if (StringUtil.isNotEmpty(annealer.getId())) {
			annealer=annealerService.getEntity(AnnealerEntity.class, annealer.getId());
			String[] id_s=annealer.getFhbid().split(",");
			for (String id : id_s) {
				ProcessReportEntity processReport = processReportService.getEntity(ProcessReportEntity.class, id);
				list.add(processReport);
			}
			String nprocess = list.get(0).getNprocess();
			req.setAttribute("nprocess", nprocess);
			List<WorkshopEntity> workshopList = workshopService.findWorkshopList();
			req.setAttribute("workshopList", workshopList);
		
			req.setAttribute("processReportList", list);
			req.setAttribute("annealerPage", annealer);
		}
		return new ModelAndView("yongxin/process/annealerReport_p4");
	}
	
	
	/**
	 * 工序汇报列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addtemp")
	public ModelAndView addtemp(AnnealerEntity annealer, HttpServletRequest req) {
		
		// 炉号id
		String lid = req.getParameter("id");
		
		if (StringUtil.isNotEmpty(lid)) {
			String hql = "from TempRecordEntity where 1 = 1 and flid = ?";
			List<TempRecordEntity> list = systemService.findHql(hql, lid);
			req.setAttribute("flid", lid);
			
			req.setAttribute("TempRecordList", list);
		}
		
		return new ModelAndView("yongxin/process/annealerTempReport_p4");
	}
	
	
	

	/**
	 * 添加工序汇报
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "savetemp")
	@ResponseBody
	public AjaxJson savetemp(TempRecordEntity tempRecord, AnnealerEntity annealer,HttpServletRequest request) {
		
		
		AjaxJson j = new AjaxJson();
		message = "记录完成";
		systemService.save(tempRecord);
		
		j.setMsg(message);
		return j;
	}
	
	
	/**
	 * 添加工序汇报
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "getProcess")
	@ResponseBody
	public AjaxJson getProcess(ProcessReportEntity processReport, HttpServletRequest request) {
	
		
		String fbcph=request.getParameter("fbcph");
		String ofbcph="";
		if(fbcph!=null && fbcph.indexOf("-")>0){
			ofbcph=fbcph.substring(0,fbcph.indexOf("-"));
		}
		Object[] object=new Object[2];
		object[0]=fbcph;
		object[1]=ofbcph;
		
		
		String sql="select tp.fbcph,tp.fprocess,tp.create_date,dic.typename from t_process tp ";
		sql +=" left join (select tst.typecode,tst.typename from t_s_type tst,t_s_typegroup tstg ";
		sql +=" where tst.typegroupid=tstg.ID ";
		sql +=" and tstg.typegroupcode='ccgx') dic ";
		sql +=" on tp.fprocess=dic.typecode ";
		sql +=" where fbcph=? or fbcph=? ";
		sql +=" order by tp.create_date ";
		
		
		String sql2="select tst.typecode,tst.typename from t_s_type tst,t_s_typegroup tstg ";
		sql2 +=" where tst.typegroupid=tstg.ID ";
		sql2 +=" and tstg.typegroupcode='ccgx'";
		
		List<Map<String,Object>> maplist=null;
		List<Map<String,Object>> maplist2=null;
		 try{
			 maplist=systemService.findForJdbc(sql, object);
			 maplist2=systemService.findForJdbc(sql2,null);
		 }
		 catch(Exception ex){
			 
		 }
		 finally{
			
		 }
		 AjaxJson j = new AjaxJson();
		 j.setObj(maplist);
		 j.setMsg(createSelecte(maplist2));
		 
		return j;
	}
	
	private String createSelecte(List<Map<String,Object>> maplist){
		String select="<select id='nprocess' name='nprocess'><option value=''>请选择</option>";
		for (Map<String, Object> map : maplist) {
			select +="<option value="+map.get("typecode")+">"+map.get("typename")+"</option>";
		}
		select = select.replaceAll(select.substring(67,98), "");
		return select;
	}
	
	
	private String lpad(String org,String str,String len){
		
		org = String.format("%"+len+"s",org);
		org = org.replaceAll("\\s", str);
		System.out.println("-"+org+"-");
		
		return org;
	}
	
	
}
